package com.example.shop_2211.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.base.mvvm.BaseFragment
import com.example.shop_2211.R
import com.example.shop_2211.adapter.OneAdapter
import com.example.shop_2211.adapter.TwoAdapter
import com.example.shop_2211.databinding.FragmentCategoryBinding
import com.example.shop_2211.fgViewModel.CategoryViewModel

class CategoryFragment : BaseFragment<FragmentCategoryBinding,CategoryViewModel>() {
    lateinit var oneAdapter: OneAdapter
    lateinit var twoAdapter: TwoAdapter
    //定义一个全局变量，用来显示是否是点击滑动的
    var isClick = false
    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(context)

        twoAdapter = TwoAdapter()
        binding.rvTwo.adapter = twoAdapter
        val layoutManager = LinearLayoutManager(context)
        binding.rvTwo.layoutManager = layoutManager

        viewModel.category()
        //点击一个分类 文字颜色发生变化，同时 二级分类对应内容置顶
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            oneAdapter.setId(oneAdapter.data[position].id)
            isClick = true//点击时，
            layoutManager.scrollToPositionWithOffset(position,0)
            isClick = false//点击引发的滑动接收后
        }
        //滑动二级分类，一级分类随之变化
        binding.rvTwo.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(!isClick){
                    //自己滑动
                    val itemPosition = layoutManager.findFirstVisibleItemPosition()//找到当前可见第一个下标
                    if(twoAdapter.data[itemPosition].id!=oneAdapter.selectId){
                        //两边id不相同
                        oneAdapter.setId(twoAdapter.data[itemPosition].id)//更新一下选中的文字颜色
                        binding.rvOne.scrollToPosition(itemPosition)//滑动一下
                    }

                }
            }
        })
    }

    override fun initData() {
        viewModel.success.observe(this){
            if(it.code==200){
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()

                twoAdapter.data.clear()
                twoAdapter.data.addAll(it.data)
                twoAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun getViewModel(): Class<CategoryViewModel> = CategoryViewModel::class.java

    override fun getLayout() = R.layout.fragment_category

}